﻿using HandyControl.Controls;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using HandyControl.Data;
using System;
using IOPath = System.IO.Path;
using UIPath = System.Windows.Shapes.Path;
using Newtonsoft.Json.Linq;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Windows.Media.Animation;
using System.Linq;


namespace 酉阳AI
{
    public partial class MainWindow : HandyControl.Controls.Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Height = 694;
            Width = 846;
            ResizeMode = ResizeMode.CanMinimize; // 大小不可调整
            模型.SelectedIndex = 0;  //默认选中
            指导.Next(); //下一步
            加载动画.Visibility = Visibility.Collapsed; //默认隐藏加载动画
            状态.Visibility = Visibility.Collapsed; //默认隐藏状态
            MessageSender.SendMessage("欢迎使用！", EnumAlarmType.Info); //右边栏消息
            // Growl.Clear(); //关闭通知

        }


        private void AnimationCompleted(object sender, EventArgs e)
        {
            // 过渡动画完成后执行的操作
        }

        public static class MessageSender
        {
            public static void SendMessage(string message, EnumAlarmType alarmType)
            {
                if (alarmType == EnumAlarmType.Info)
                {
                    HandyControl.Controls.Growl.Info(message);
                }
                else if (alarmType == EnumAlarmType.Warning)
                {
                    HandyControl.Controls.Growl.Warning(message );
                }
                else if (alarmType == EnumAlarmType.Err)
                {
                    HandyControl.Controls.Growl.Error(message);
                }
                else if (alarmType == EnumAlarmType.Fatal)
                {
                    HandyControl.Controls.Growl.Fatal(message);
                }
                else
                {
                    HandyControl.Controls.Growl.Info(message);
                }
            }
        }

        public enum EnumAlarmType
        {
            Debug = 0,
            Info,
            Err,
            Fatal,
            Warning,
        }

        //public class GrowlEvent : PubSubEvent<GrowMsg>
        //{
        //}

        public class GrowMsg
        {
            public EnumAlarmType enumAlarmType;
            public string message;
            public string token;
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                指导.Next(); //下一步

                //禁用下载按钮，防止重复点击
                开始绘画.IsEnabled = false;

                //显示加载动画及状态
                加载动画.Visibility = Visibility.Visible;
                状态.Visibility = Visibility.Visible;
                状态.Text = "正在请求";
                string selectedModel = ((ComboBoxItem)模型.SelectedItem).Content.ToString();
                状态.Text = "AI正在拼命绘画中";
                string imageDescription = 描述.Text;

                if (!string.IsNullOrEmpty(selectedModel) && !string.IsNullOrEmpty(imageDescription))
                {
                    string apiUrl = "";
                    if (selectedModel == "sd模型-动漫风格")
                    {
                        apiUrl = "https://api.lolimi.cn/API/AI/sd.php?msg=" + imageDescription + "&mode=动漫";
                    }
                    else if (selectedModel == "sd模型-写实风格")
                    {
                        apiUrl = "https://api.lolimi.cn/API/AI/sd.php?msg=" + imageDescription + "&mode=写实";
                    }

                    using (var client = new HttpClient())
                    {
                        var response = await client.GetAsync(apiUrl);
                        if (response.IsSuccessStatusCode)
                        {
                            byte[] imageData = await response.Content.ReadAsByteArrayAsync();
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = new MemoryStream(imageData);
                            bitmapImage.EndInit();
                            //显示图片到Border
                            Image image = new Image();
                            image.Source = bitmapImage;
                            image.Stretch = Stretch.UniformToFill; //铺满
                            image.Width = 输出图片.ActualWidth;
                            image.Height = 输出图片.ActualHeight;
                            输出图片.Child = image; //写入
                            开始绘画.IsEnabled = true;
                            MessageSender.SendMessage("绘画完毕(≧∀≦)", EnumAlarmType.Info); //右边栏消息
                            加载动画.Visibility = Visibility.Collapsed; //隐藏加载动画
                            状态.Visibility = Visibility.Collapsed; //隐藏状态
                            指导.Next(); //下一步
                        }
                    }
                }
                else
                {
                    //Growl.Success("请选择模型并填写图片描述！", "SuccessMsg"); 闪退暂不使用
                }
            }
            catch (NotSupportedException ex)
            {
                //显示错误消息给用户
                MessageSender.SendMessage("发生错误，服务器已关闭", EnumAlarmType.Err); //右边栏消息
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                //清空绘画区域
                输出图片.Child = null;

                //恢复按钮状态
                开始绘画.IsEnabled = true;

                //隐藏加载动画和状态
                加载动画.Visibility = Visibility.Collapsed;
                状态.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                //显示通用错误消息给用户
                MessageSender.SendMessage("发现未知错误，请联系开发者！", EnumAlarmType.Err); //右边栏消息
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                //清空绘画区域
                输出图片.Child = null;

                //恢复按钮状态
                开始绘画.IsEnabled = true;

                //隐藏加载动画和状态
                加载动画.Visibility = Visibility.Collapsed;
                状态.Visibility = Visibility.Collapsed;
            }
        }
        private CancellationTokenSource cancellationTokenSource;

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //取消异步请求
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }

            //清空绘画区域
            输出图片.Child = null;

            //恢复按钮状态
            开始绘画.IsEnabled = true;

            //隐藏加载动画和状态
            加载动画.Visibility = Visibility.Collapsed;
            状态.Visibility = Visibility.Collapsed;

            //发送消息
            MessageSender.SendMessage("绘画已停止", EnumAlarmType.Info);
        }

        private string output; //存储AI的回复
        private bool isAiStopped = false; //布尔值判断是否请求API

        private async void 发送内容_Click(object sender, RoutedEventArgs e) //ChatGPT3.5 需要使用此将函数名更改为 发送内容_Click 即可
        {
            string userInput = 聊天内容.Text;

            if (isAiStopped)
            {
                ReplaceMessageInUI("正在思考中...", "已停止");
                return;
            }

            if (!string.IsNullOrEmpty(userInput))
            {
                //禁用发送按钮
                发送内容.IsEnabled = false;
                发送内容.Content = "正在生成"; //改变文本

                //显示用户输入的消息
                AddMessageToUI(userInput, false);

                //显示"正在思考中..."的消息
                string thinkingMessage = "正在思考中...";
                AddMessageToUI(thinkingMessage, true);

                //调用mfcat3.5 API获取AI回复
                string apiUrl = "https://api.lolimi.cn/API/AI/mfcat3.5.php?msg=" + userInput;

                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        string responseData = await response.Content.ReadAsStringAsync();

                        //替换"正在思考中..."的消息为AI的实际回复
                        ReplaceMessageInUI(thinkingMessage, responseData);
                    }
                    else
                    {
                        //可以添加处理API调用失败的逻辑
                        ReplaceMessageInUI(thinkingMessage, "抱歉，未能获取到有效回复。");
                    }
                }

                //启用发送按钮
                发送内容.IsEnabled = true;

                聊天内容.Text = ""; //清空输入框
            }
        }

        private async void 文心一言(object sender, RoutedEventArgs e)  //文心一言，需要使用此更换为发送内容_Click即可
        {
            string userInput = 聊天内容.Text;

            if (isAiStopped)
            {
                ReplaceMessageInUI("正在思考中...", "已停止");
                return;
            }

            if (!string.IsNullOrEmpty(userInput))
            {
                //禁用发送按钮
                发送内容.IsEnabled = false;
                发送内容.Content = "正在生成"; //改变文本

                //显示用户输入的消息
                AddMessageToUI(userInput, false);

                //显示"正在思考中..."的消息
                string thinkingMessage = "正在思考中...";
                AddMessageToUI(thinkingMessage, true);

                //调用API接口获取AI回复
                string apiUrl = "https://api.lolimi.cn/API/AI/wx.php?msg=" + userInput; //文心一言API


                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        string responseData = await response.Content.ReadAsStringAsync();  
                        dynamic data = JObject.Parse(responseData); 
                        output = data.data.output; //更新类级别的output字段，避免true文  

                        if (!string.IsNullOrEmpty(output))
                        {
                            //替换"正在思考中..."的消息为AI的实际回复
                            ReplaceMessageInUI(thinkingMessage, output);
                        }
                        else
                        {
                            //可以添加超时逻辑或者直接显示默认提示信息
                            ReplaceMessageInUI(thinkingMessage, "抱歉，未能获取到有效回复。");
                        }
                    }
                }

                //启用发送按钮
                发送内容.IsEnabled = true;

                聊天内容.Text = ""; //清空输入框
            }
        }

        private void AddMessageToUI(string message, bool isResponse)
        {
            StackPanel messagePanel = new StackPanel();
            Border messageBubble = new Border();
            TextBlock messageText = new TextBlock();

            messageBubble.Padding = new Thickness(10);
            messageBubble.CornerRadius = new CornerRadius(10);
            messageText.Text = message;
            messageText.TextWrapping = TextWrapping.Wrap;

            //添加 YouAI 文本到气泡左上角
            TextBlock youAiText = new TextBlock();
            youAiText.Text = "YouAI";
            youAiText.Foreground = new SolidColorBrush(Colors.Gray); //设置文本颜色为灰色
            youAiText.HorizontalAlignment = HorizontalAlignment.Left;
            youAiText.Margin = new Thickness(10, 0, 0, 0); //调整位置
            messagePanel.Children.Add(youAiText);

            //设置消息气泡的样式
            if (isResponse)
            {
                // AI回答气泡
                messageBubble.Background = new SolidColorBrush(Color.FromArgb(0xDD, 0xDD, 0xDD, 0xDD)); //灰白
                messagePanel.HorizontalAlignment = HorizontalAlignment.Left;
                messagePanel.Margin = new Thickness(12, 0, 0, 10); //左空隙12，气泡间空隙10
            }
            else
            {
                //用户气泡
                messageBubble.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC)); //浅蓝
                messageText.Foreground = new SolidColorBrush(Colors.White);
                messagePanel.HorizontalAlignment = HorizontalAlignment.Right;
                messagePanel.Margin = new Thickness(0, 0, 12, 10); //左空隙12，气泡间空隙10
            }


            messageBubble.Child = messageText;
            messagePanel.Children.Add(messageBubble);

            //将消息显示控件添加到布局中
            //StackPanel存放消息
            messageContainer.Children.Add(messagePanel);

            //如果是AI的回复消息，则滚动到最新的消息
            if (isResponse)
            {
                //滚动到最新的消息
                messageScrollViewer.ScrollToVerticalOffset(messageScrollViewer.ExtentHeight);
            }
        }


        string author = "Fangzhi";
        private void ReplaceMessageInUI(string oldMessage, string newMessage)
        {
            foreach (StackPanel messagePanel in messageContainer.Children)
            {
                foreach (var childElement in messagePanel.Children)
                {
                    if (childElement is Border messageBubble)
                    {
                        var innerContent = messageBubble.Child;
                        if (innerContent is TextBlock textBlock && textBlock.Text == oldMessage)
                        {
                            textBlock.Text = newMessage;
                            发送内容.Content = "发送"; //改变文本

                            messageBubble.MouseRightButtonDown += (sender, e) =>
                            {
                                ContextMenu menu = new ContextMenu();

                                MenuItem copyMenuItem = new MenuItem();
                                copyMenuItem.Header = "复制";
                                copyMenuItem.Click += (copySender, copyArgs) =>
                                {
                                    Clipboard.SetText(newMessage);
                                };

                                menu.Items.Add(copyMenuItem);
                                messageBubble.ContextMenu = menu;
                            };

                            return;
                        }
                    }
                }
            }
        }

        private void Stop1(object sender, RoutedEventArgs e)
        {
            //取消异步请求
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }

            //设置AI已停止标志
            isAiStopped = true;

            //启用发送按钮
            发送内容.IsEnabled = true;

            //将AI气泡回复文本变更为"已停止"
            ReplaceMessageInUI("正在思考中...", "已停止");

            MessageSender.SendMessage("已取消请求😘", EnumAlarmType.Info);
            发送内容.Content = "发送"; //改变文本
            聊天内容.Text = ""; // 清空输入框

            //重置AI未停止标志
            isAiStopped = false;
        }

        private void 聊天内容_KeyDown(object sender, KeyEventArgs e) //回车发送文本
        {
            if (e.Key == Key.Enter)
            {
                发送内容_Click(sender, e);
                聊天内容.Text = string.Empty; //清空聊天框
            }
        }

    }
}



